const gulp = require('gulp')
const sass = require('gulp-sass')
const autoprefixer = require('gulp-autoprefixer')
const browserSync = require('browser-sync').create()
const watch = require('gulp-watch')
const notify = require("gulp-notify")
const uglify = require('gulp-uglify')
var fileinclude = require('gulp-file-include')
var sourcemaps = require('gulp-sourcemaps')
// 错误提示函数
const handleErrors = function () {

  var args = Array.prototype.slice.call(arguments);

  notify.onError({title: 'compile error', message: '<%=error.message %>'}).apply(this, args); //替换为当前对象

  this.emit(); //提交
}
gulp.task('style', [ 'sass'])
gulp.task('sass', function () {
  return gulp.src('./dist/css/*.scss').
  pipe(sourcemaps.init()). //编译scss
  pipe(sass()).
   on('error', handleErrors).
  pipe(sourcemaps.write()). //交给notify处理错误
  pipe(autoprefixer({browsers: ['last 10 versions']})). //自动加前缀
  on('error', handleErrors).
  pipe(gulp.dest('./dist/css/'))
})
// server
const server = require('./config.json').server
const proxy = require('./config.json').proxy
const port = require('./config.json').port
gulp.task('browserSync', function () {

  var files = ['./dist/*.html', './dist/css/*.css', './dist/img/*.jpg', './dist/img/*.png']
  browserSync.init(files, {
    port: port,
    ghostMode: false,
    open: false,
    server: server
  })
})
gulp.task('fileinclude', function() {
  return gulp.src('./dist/templates/*.html')
  .pipe(fileinclude({
    prefix: '@@',
    basepath: '@file'
  }))
  .on('error', handleErrors)
  .pipe(gulp.dest('./dist/'));
});

gulp.task('default', ['browserSync','style'], function () {
  gulp.watch('./dist/css/*.scss', ['style'])
  gulp.watch('./dist/css/*.less', ['style'])
  gulp.watch('./dist/img/*')
  gulp.watch(['./dist/templates/*.html','./dist/templates/components/*.html'], ['fileinclude']);
  // gulp.watch('./config.json',function(){
  //   const server = require('./config.json').server;
  //   const port = require('./config.json').port;
  //   browserSync.reload(['']);
  // })
  // watch('./dist/img/*', ['img'])
})
gulp.task('js', function () {
  return gulp.src('./dist/libs/*.js'). //
  pipe(uglify({
    mangle: true, //类型：Boolean 默认：true 是否修改变量名
    compress: true, //类型：Boolean 默认：true 是否完全压缩
  })). //压缩
  pipe(gulp.dest('./libs/'));
})
